package com.hengtongxing.hejiayun.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hengtongxing.hejiayun.MainActivity;
import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.BaseActivity;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.LoginBean;
import com.hengtongxing.hejiayun.bean.UserInfoBean;
import com.hengtongxing.hejiayun.event.LoginEvent;
import com.hengtongxing.hejiayun.login.adapter.TipsMobileListAdapter;
import com.hengtongxing.hejiayun.login.model.ILoginModel;
import com.hengtongxing.hejiayun.login.model.LoginModelImpl;
import com.hengtongxing.hejiayun.mine.UserAgreementActivity;
import com.hengtongxing.hejiayun.mine.model.MineModelImpl;
import com.hengtongxing.hejiayun.utils.PopWinDownUtil;
import com.hengtongxing.hejiayun.utils.SPManager;
import com.hengtongxing.hejiayun.utils.ToastUtil;
import com.hengtongxing.hejiayun.widget.ViewLoading;
import com.hengtongxing.hejiayun.widget.WrapContentLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.cb_display)
    CheckBox cbDisplay;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.cb_remember)
    CheckBox cbRemember;
    @BindView(R.id.edit_mobile)
    EditText editMobile;
    @BindView(R.id.edit_pwd)
    EditText editPwd;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.cb_agreement)
    CheckBox cb_agreement;
    @BindView(R.id.tv_service_agreement)
    TextView tv_service_agreement;
    @BindView(R.id.tv_privacy_policy)
    TextView tv_privacy_policy;

    private ILoginModel loginModel;
    private PopWinDownUtil popWinDownUtil;
    private List<String> mobileList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(true, 0.2f).init();
        initView();
        showHostory();
    }

    public void initView() {
        loginModel = new LoginModelImpl();
        //点击眼隐藏或显示密码
        cbDisplay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //选择状态 显示明文--设置为可见的密码
                    editPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    editPwd.setSelection(editPwd.getText().toString().length());
                } else {
                    //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                    editPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    editPwd.setSelection(editPwd.getText().toString().length());
                }
            }
        });
        String moblie = SPManager.getInstance().getUserMobile();
        String pwd = SPManager.getInstance().getUserPwd();
        if (!TextUtils.isEmpty(moblie) && !TextUtils.isEmpty(pwd)) {
            editMobile.setText(moblie);
            editMobile.setSelection(moblie.length());
            editPwd.setText(pwd);
            editPwd.setSelection(pwd.length());
            cbRemember.setChecked(true);
        }
        editMobile.setOnClickListener(v -> {
            if (mobileList.size() > 0 && !popWinDownUtil.isShowing()) {
                popWinDownUtil.show();
            }
        });
        editMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    if (mobileList.size() > 0 && !popWinDownUtil.isShowing()) {
                        popWinDownUtil.show();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        tv_service_agreement.setOnClickListener(v -> {
            Intent intent = new Intent(this, UserAgreementActivity.class);
            intent.putExtra("type", 1);
            startActivity(intent);
        });
        tv_privacy_policy.setOnClickListener(v -> {
            Intent intent = new Intent(this, UserAgreementActivity.class);
            intent.putExtra("type", 2);
            startActivity(intent);
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        mobileList.clear();
        String search_record = SPManager.getInstance().getSearchRecord();
        if (!TextUtils.isEmpty(search_record)) {
            String[] split = search_record.split(",");
            Collections.addAll(mobileList, split);
        }
    }

    public void requesLogin() {
        String mobile = editMobile.getText().toString();
        String password = editPwd.getText().toString();
        if (TextUtils.isEmpty(mobile)) {
            ToastUtil.showShort("请输入用户名");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.showShort("请输入密码");
            return;
        }
        boolean checked = cb_agreement.isChecked();
        if (!checked) {
            Toast.makeText(this, "请勾选同意《服务协议》和《隐私政策》", Toast.LENGTH_SHORT).show();
            return;
        }
        ViewLoading.showProgress(mActivity, "登录中......");
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        loginModel.requestLoginByPwd(mobile, password, pushService.getDeviceId(), new DataCallBack<LoginBean>() {
            @Override
            public void onSuccessful(LoginBean bean) {
                SPManager.getInstance().saveToken(bean.getData().getAccess_token());
                ToastUtil.showShort(bean.getMsg());
                EventBus.getDefault().post(new LoginEvent());
                requestUserInfo();
                if (cbRemember.isChecked()) {
                    SPManager.getInstance().saveUserMobile(mobile);
                    SPManager.getInstance().saveUserPwd(password);
                } else {
                    SPManager.getInstance().saveUserMobile("");
                    SPManager.getInstance().saveUserPwd("");
                }
                SPManager.getInstance().saveSearchRecord(mobile + "_" + password);
                showActivity(MainActivity.class);
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestUserInfo() {
        new MineModelImpl().requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {
                SPManager.getInstance().saveUserInfoJson(new Gson().toJson(bean));
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void showHostory() {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.pop_history_list, null);
        popWinDownUtil = new PopWinDownUtil(mActivity, view, editMobile);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        TipsMobileListAdapter listAdapter = new TipsMobileListAdapter(mobileList);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnCallBackListener(data -> {
            if (!TextUtils.isEmpty(data)) {
                String[] split = data.split("_");
                if (split.length == 2) {
                    editMobile.setText(split[0]);
                    editMobile.setSelection(split[0].length());
                    editPwd.setText(split[1]);
                    editPwd.setSelection(split[1].length());
                }
                if (split.length == 1) {
                    editMobile.setText(split[0]);
                    editMobile.setSelection(split[0].length());
                }
                popWinDownUtil.hide();
            }
        });
    }

    @OnClick({R.id.tv_login, R.id.tv_forget_pwd, R.id.tv_register_account})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                requesLogin();
                break;
            case R.id.tv_forget_pwd:
                showActivity(ForgetPwdActivity.class);
                break;
            case R.id.tv_register_account:
                showActivity(RegisterActivity.class);
                break;
        }
    }
}
